package com.pms.repair.web;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.exception.R;
import com.pms.partitionPoints.entity.KyEquipmentInfo;
import com.pms.partitionPoints.service.IKyEquipmentInfoService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.repair.entity.KyRechargeHistoricalRecords;
import com.pms.repair.service.IKyRechargeHistoricalRecordsService;
import com.pms.util.idutil.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.repair.service.IKyCardRechargeService;
import com.pms.repair.entity.KyCardRecharge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.*;
@RestController
@RequestMapping("/pip/kyCardRecharge")
@Api(value="数据库充值表",description = "数据库充值表")
public class KyCardRechargeController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IKyCardRechargeService kyCardRechargeService;
    @Autowired
    IKyEquipmentInfoService kyEquipmentInfoService;
    @Autowired
    IKyRechargeHistoricalRecordsService rechargeHistoricalRecordsService;

    /**
     * 数据卡充值
     * @param equipmentInfoId
     * @param recentlyCurrentBalance
     * @param recentlyName
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "数据卡充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name="equipmentInfoId",value="设备ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="recentlyCurrentBalance",value="充值总额",required = true,dataType = "BigDecimal",paramType="form"),
            @ApiImplicitParam(name="recentlyName",value="最近充值人",required = true,dataType = "String",paramType="form"),
    })
    public R add(Long equipmentInfoId,BigDecimal recentlyCurrentBalance, String recentlyName){
        parameterIsNull(equipmentInfoId,"请填写设备ID");
        parameterIsNull(recentlyCurrentBalance,"充值金额不能为空");
        parameterIsNull(recentlyName,"充值人不能为空");
        //查询测点信息
        KyEquipmentInfo eq=kyEquipmentInfoService.selectById(equipmentInfoId);
        if (eq==null){return  R.error(400,"测点信息不存在");}
        KyCardRecharge entity=kyCardRechargeService.selectOne(new EntityWrapper<KyCardRecharge>().eq("equipment_info_id",equipmentInfoId));
        //第一次没有充值记录的时候
        if (entity!=null){
            KyRechargeHistoricalRecords  records=new KyRechargeHistoricalRecords();
            records.setCurrentMoney(entity.getCurrentBalance().add(recentlyCurrentBalance));
            entity.setTotalAmount(entity.getTotalAmount().add(recentlyCurrentBalance));//充值总额
            entity.setCurrentBalance(entity.getCurrentBalance().add(recentlyCurrentBalance));//剩余金额
            entity.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            entity.setRecentlyData(new Date());//最近充值时间
            entity.setRecentlyName(recentlyName);//最近充值人
            entity.setUpdTime(new Date());//操作时间
            entity.setUpdUser(getCurrentUserMap().get("userName"));//操作人
            int y = entity.getCurrentBalance().compareTo(entity.getMonthlyFeeStandard());
            if(entity.getCurrentBalance().signum()==-1){
                entity.setState(3);//欠费
            }else if (y==1||y==0){
                entity.setState(1);//正常
            }else if (y==-1){
                entity.setState(2);//余额不足
            }
            records.setCardId(entity.getCardId());
            records.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            records.setRecentlyData(new Date());//最近充值时间
            records.setRecentlyName(recentlyName);//最近充值人
            records.setEquipmentInfoId(equipmentInfoId);//设备ID
            records.setCrtUser(getCurrentUserMap().get("userName"));
            records.setCrtTime(new Date());
            rechargeHistoricalRecordsService.insert(records);
            kyCardRechargeService.updateById(entity);
        }else{
            Long cardId=new SnowFlake(0,0).nextId();
            entity.setCardId(cardId);
            entity.setCurrentBalance(recentlyCurrentBalance);//剩余余额
            entity.setTotalAmount(recentlyCurrentBalance);
            entity.setEquipmentInfoName(eq.getName());
            entity.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            entity.setRecentlyData(new Date());//最近充值时间
            entity.setRecentlyName(recentlyName);//最近充值人
            entity.setEquipmentInfoName(eq.getName());//设备名称
            entity.setPhone(eq.getCardphone());//测点卡电话号码
            entity.setState(1);
            entity.setMonthlyFeeStandard(new BigDecimal(0));
            entity.setEquipmentInfoId(equipmentInfoId);//设备ID
            entity.setCrtTime(new Date());
            entity.setCrtUser(getCurrentUserMap().get("userName"));
           KyRechargeHistoricalRecords  records=new KyRechargeHistoricalRecords();
           records.setCardId(cardId);
            records.setCurrentMoney(recentlyCurrentBalance);//充值后余额
           records.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
           records.setRecentlyData(new Date());//最近充值时间
           records.setRecentlyName(recentlyName);//最近充值人
           records.setEquipmentInfoId(equipmentInfoId);//设备ID
           records.setCrtTime(new Date());
           rechargeHistoricalRecordsService.insert(records);
           kyCardRechargeService.insert(entity);
        }
        return R.ok();
    }


    /**
     * 查询单条数据信息
     * @param cardId
     * @return
     */
    @PostMapping("/findById")
    @ApiOperation(value = "查询单条数据信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cardId",value="数据卡充值ID",required = true,dataType = "Long",paramType="form"),
    })
    public R findById(Long cardId){
        parameterIsNull(cardId,"数据卡充值ID不能为空");
        KyCardRecharge cardRecharge= kyCardRechargeService.findById(cardId);
        if (null==cardRecharge){return  R.error(400,"数据卡充值信息不存在");}
        return R.ok().put("data",cardRecharge);
    }


    /**
     * 分页查询数据库充值
     * @return
     */
    @GetMapping(value = "/page")
    @ApiOperation("分页查询数据库充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "equipmentInfoId", value = "测点ID", required = true, dataType = "userId", paramType = "form"),
    })
    public R page(int limit,int page,String name,String equipmentInfoId){
        parameterIsNull(equipmentInfoId,"测点ID不能为空");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<KyCardRecharge> pages = new Page<>(page,limit);
        Wrapper<KyCardRecharge> ew=new EntityWrapper();
        if (StringUtils.isNotBlank(equipmentInfoId)){
            ew.in("c.equipment_info_id",equipmentInfoId);
        }else{
            ew.eq("c.equipment_info_id","null");
        }
        ew.and().eq("e.status",1);
        if (StringUtils.isNotBlank(name)){
            ew.and().like("c.equipment_info_name",name);
            ew.or().like("c.total_amount",name);
            ew.or().like("c.phone_",name);
            ew.or().like("c.recently_name",name);
            ew.or().like("c.state_",name);
        }
        Page<KyCardRecharge> pageList = kyCardRechargeService.selectByKyCardRechargePage(pages,ew);
        return  R.ok().put("data",pageList);
    }

    /**
     * 数据卡信息编辑
     * @param cardId
     * @param monthlyFeeStandard
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "数据卡信息编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cardId",value="数据卡充值ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="monthlyFeeStandard",value="每月收费标准",required = true,dataType = "BigDecimal",paramType="form"),
    })
    public R update(Long cardId,BigDecimal monthlyFeeStandard){
        parameterIsNull(cardId,"请填写数据卡充值ID");
        parameterIsNull(monthlyFeeStandard,"请填写每月收费标准");
        KyCardRecharge entity=kyCardRechargeService.selectById(cardId);
        parameterIsNull(entity,"数据卡充值信息不存在");
        int y = entity.getCurrentBalance().compareTo(entity.getMonthlyFeeStandard());
        if(entity.getCurrentBalance().signum()==-1){
            entity.setState(3);//欠费
        }else if (y==1||y==0){
            entity.setState(1);//正常
        }else if (y==-1){
            entity.setState(2);//余额不足
        }
        entity.setMonthlyFeeStandard(monthlyFeeStandard);
        entity.setUpdTime(new Date());
        entity.setUpdUser(getCurrentUserMap().get("userName"));
        kyCardRechargeService.updateById(entity);
        return  R.ok();
    }

    /**
     * 查询历史数据
     * @param equipmentInfoId
     * @return
     */
    @PostMapping("/getHistoricalData")
    @ApiOperation(value = "查询历史数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="equipmentInfoId",value="设备ID",required = true,dataType = "Long",paramType="form"),
    })
    public R getHistoricalData(Long equipmentInfoId){
        parameterIsNull(equipmentInfoId,"请填写设备ID");
        List<KyRechargeHistoricalRecords> list =rechargeHistoricalRecordsService.selectListByData(equipmentInfoId);
        return  R.ok().put("data",list);
    }


}